import { Form, Input, InputNumber, Popconfirm, Table, Typography, Button } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import React, { useEffect, useRef, useState } from 'react';
import { Tag } from 'antd';
import './Index.scss'
import { getTeacher } from '../../apis/employee'
import { changeInfo } from '../../apis/employee'
import { deleteTeacher } from '../../apis/employee'
import { AddEmployee } from '../../components/EmployeeModal'
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { changeDrawer } from '../../store/modules/drawer';

interface Item {
  key: string;
  id: string;
  name: string;
  distance: number;
  clickNum: number,
  img: string,
  complaints: number,
  price: number,
  workState: number,
  tags: string[];
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}! `,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const App: React.FC = () => {
  const dispatch=useAppDispatch()
  // const visible=useAppSelector(state=>state.drawer.visible)
  const [employee, setEmployee] = useState([])
  const originData: Item[] = []
  async function getEmployee() {
    let res: any = await getTeacher()
    setEmployee(res.data)
  }
  useEffect(() => {

    getEmployee()

  }, [])

  for (let i = 0; i < employee.length; i++) {
    originData.push({
      key: employee[i]["id"],
      id: employee[i]["id"],
      name: employee[i]["name"],
      distance: employee[i]["distance"],
      clickNum: employee[i]["clickNum"],
      img: employee[i]["img"],
      complaints: employee[i]["complaints"],
      price: employee[i]["price"],
      workState: employee[i]["workState"],
      tags: employee[i]["tags"],
    })
  }

  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  useEffect(() => {
    setData(originData)
  }, [originData])

  const [editingKey, setEditingKey] = useState('');
  const finish=()=>{
    getEmployee()
  }


  const isEditing = (record: Item) => record.key === editingKey;

  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({ id: '', name: '', distance: '', clickNum: '', img: '', complaints: '', price: '', workState: '', tags: [], ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields());

      console.log(row);
      console.log(typeof row.tags);

      if (typeof row.tags === "string") {
        row.tags = row.tags.split(",")
      }
      console.log(row);
      changeInfo(key.toString(), "PUT", row).then(res => console.log("res", res))

      const newData = [...data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('验证失败:', errInfo);
    }
    // window.location.reload()
    getEmployee()
  };


  const columns = [
    {
      title: '工号',
      dataIndex: 'id',
      width: '7%',
      editable: false,
      ellipsis: true,

    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: '10%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '距离',
      dataIndex: 'distance',
      width: '11%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '点赞',
      dataIndex: 'clickNum',
      width: '7%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '投诉',
      dataIndex: 'complaints',
      width: '7%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: '7%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'workState',
      width: '7%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '照片',
      dataIndex: 'img',
      width: '6%',
      editable: true,
      ellipsis: true,
    },
    {
      title: '标签',
      key: 'tags',
      width: '15%',
      dataIndex: 'tags',
      editable: true,
      ellipsis: true,
      render: (_: any, { tags }: { tags: string[] }) => (
        <>
          {tags.map((tag: any) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      //添加员工
      title: <>操作 </>,
      dataIndex: 'operation',
      width: '15%',
      // fixed:"right",
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return (
          <>
            {
              editable ? (
                <span>
                  <Typography.Link onClick={() => save(record.key)} style={{ marginRight: 8, }}>
                    保存
                  </Typography.Link>
                  <Popconfirm title="确定取消吗?" onConfirm={cancel}>
                    <a>取消</a>
                  </Popconfirm>
                </span>
              ) : (
                <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                  Edit
                </Typography.Link>
              )
            }
            <Popconfirm
              title="确定删除此数据吗"
              onConfirm={() => {
                deleteTeacher(record.key).then(res => {
                  getEmployee()
                })
              }}
              onCancel={() => { }}
              okText="确定"
              cancelText="取消"
            >
              <Button danger shape="circle" style={{ marginLeft: 10 }} icon={<DeleteOutlined />} />
            </Popconfirm>
          </>
        )
      },
    },
  ];

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: col.dataIndex === 'price' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <>
      <AddEmployee finish={finish}/>
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        scroll={{ x:1200 }}
        pagination={{
          defaultPageSize:9,
          position: ["bottomCenter"],
          onChange: cancel,
        }}
      />
    </Form>
  
    </>
  );
};

export default App;

